package by.hqsoftware.RollingBall;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import by.hqsoftware.RollingBall.GraphicElements.Field;

import android.content.Context;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLU;

public class GameRenderer implements Renderer {

	public GameRenderer(Context context, Field field) {				
		mField = field;				
	}
		
	private Field mField;
	
	@Override
	public void onDrawFrame(GL10 gl) {
		// Clears the screen and depth buffer.
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		// Replace the current matrix with the identity matrix
		gl.glLoadIdentity();
		// Translates 4 units into the screen.
		gl.glTranslatef(0, 0, -33);		
		
		// Draw our scene.		
		mField.draw(gl);
		mField.getBall().draw(gl);
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		// Sets the current view port to the new size.
		gl.glViewport(0, 0, width, height);
		// Select the projection matrix
		gl.glMatrixMode(GL10.GL_PROJECTION);
		// Reset the projection matrix
		gl.glLoadIdentity();
		// Calculate the aspect ratio of the window
		GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f,
				100.0f);
		// Select the modelview matrix
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		// Reset the modelview matrix
		gl.glLoadIdentity();	
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		// Set the background color to black ( rgba ).
		gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		// Enable Smooth Shading, default not really needed.
		gl.glShadeModel(GL10.GL_SMOOTH);
		// Depth buffer setup.
		gl.glClearDepthf(1.0f);
		// Enables depth testing.
		gl.glEnable(GL10.GL_DEPTH_TEST);
		// The type of depth testing to do.
		gl.glDepthFunc(GL10.GL_LEQUAL);
		// Really nice perspective calculations.
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
		
		//enable lightning
		gl.glEnable(GL10.GL_LIGHTING);

		//enable 1st light
		gl.glEnable(GL10.GL_LIGHT0);
		
		// define the ambient component
		final float light0Ambient[] = {0.1f, 0.1f, 0.1f, 1.0f};
		gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, Converter.toBuffer(light0Ambient));
		
		// define the diffuse component
		final float light0Diffuse[] = {0.7f, 0.7f, 0.7f, 1.0f};
		gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, Converter.toBuffer(light0Diffuse));
		
		// define specular component and shininess
		final float light0Specular[] = {0.7f, 0.7f, 0.7f, 1.0f};		
		
		gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_SPECULAR, Converter.toBuffer(light0Specular));
		
		// define position of the first light
		final float light0Position[] = {5.0f, 5.0f, 0.0f, 0.0f};
		gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, Converter.toBuffer(light0Position));
		
					
	}

}
